<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>js实现放大镜效果</title>
	</head>
	<style>
		.box{
			position: relative;
		}
		.box-left{
			width: 345px;
			height: 345px;
			
		}
		.box-left img{
			width: 100%;
			height: 100%;
			
		}
		.slider{
			display: none;
			width: 172.5px;
			height: 172.5px;
			position: absolute;
			background-color: rgba(255,255,255,0.3);
			/* cursor: default; */
		}
		.box-right{
			display: none;
			width: 345px;
			height: 345px;
			position: absolute;
			left: 360px;
			top:0px;
			overflow:hidden;
		}
		.right-img{
			position: absolute;
		}
	</style>
	<body>
		<!-- 左侧缩小一倍，右侧原图 -->
		<div class="box">
			<div class="box-left">
				<span class="slider"></span>
				<img src="9.jpg" />
			</div>
			<div class="box-right">
				<img class="right-img" src="9.jpg"  width="690" height="690"/>
			</div>
		</div>
		<script type="text/javascript">
			window.onload=function(){
				//封装选择器
				function $(selector){
					return document.querySelector(selector);
				}
				//获取滑块元素
				var slider=$(".slider");
				//获取右侧的div
				var box_right=$(".box-right");
				//获取左侧的div 
				var box_left=$(".box-left");
				//获取右侧div内的img图片
				var right_img=$(".right-img");
				//鼠标移动事件
				$(".box-left").onmousemove=function(e){
					
					//滑块和div显示
					slider.style.display="block";
					box_right.style.display="block";
					//改变滑块的位置(将鼠标的坐标减去滑块的宽/高的一半，)
					var slider_left=e.clientX-slider.offsetWidth/2;
					var slider_top=e.clientY-slider.offsetHeight/2;
					
					/* slider.style.top=slider_top+"px";
					slider.style.left=slider_left+"px"; */
					//使滑块的运动区域在左侧的div内
					var max_left=box_left.offsetWidth-slider.offsetWidth;
					var max_top=box_left.offsetHeight-slider.offsetHeight;
					//x轴的边界
					if(slider_left<=0){
						slider_left=0
					}else if(slider_left>max_left){
						slider_left=max_left;
					}
					//y轴的边界
					if(slider_top<0){
						slider_top=0;
					}else if(slider_top>max_top){
						slider_top=max_top;
					}
					slider.style.top=slider_top+"px";
					slider.style.left=slider_left+"px";
					//滑块移动的过程中要使右侧的图片位置发生变化
					
					right_img.style.top=-(slider_top*2)+"px";
					right_img.style.left=-(slider_left*2)+"px";
				}
				
				//鼠标移出事件
				$(".box-left").onmouseleave=function(){
					//滑块和div的隐藏
					slider.style.display="none";
					box_right.style.display="none";
				}
			}
		</script>
	</body>
</html>
